package com.asohofrucol.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.asohofrucol.dao.FormFieldDataDao;
import com.asohofrucol.dao.TechnicalAssistanceDao;
import com.asohofrucol.dao.TechnicalAssistanceItemDao;
import com.asohofrucol.dao.TechnicalAssistanceVisitDao;
import com.asohofrucol.dto.VisitDataDTO;
import com.asohofrucol.dto.VisitDataItemDTO;
import com.asohofrucol.dto.VisitDataRowDTO;
import com.asohofrucol.dto.util.VisitDataItemHelperDto;
import com.asohofrucol.model.ComboValue;
import com.asohofrucol.model.Ruat;
import com.asohofrucol.model.TechnicalAssistance;
import com.asohofrucol.model.TechnicalAssistanceField;
import com.asohofrucol.model.TechnicalAssistanceItem;
import com.asohofrucol.model.TechnicalAssistanceVisit;
import com.asohofrucol.service.TechnicalAssistanceService;

@Service("TechnicalAssistanceService")
public class TechnicalAssistanceServiceImpl implements TechnicalAssistanceService {
	@Autowired
	private TechnicalAssistanceDao technicalAssistanceDao;
	@Autowired
	private TechnicalAssistanceVisitDao technicalAssistanceVisitDao;
	@Autowired
	private TechnicalAssistanceItemDao technicalAssistanceItemDao;
	
	@Override
	public VisitDataDTO getTechniclaAssitanceVistData(Long taId) {

		VisitDataDTO visitDataDTO = new VisitDataDTO();
		TechnicalAssistance technicalAssistance = technicalAssistanceDao.findOne(taId);
		//fijar los datos en vistDataDTO que vengan de  technicalAssistance
		visitDataDTO.setId(taId);
		visitDataDTO.setAltitude(technicalAssistance.getAltitude());
		visitDataDTO.setCropArea(technicalAssistance.getCropArea());
		visitDataDTO.setNorthLatitude(technicalAssistance.getNorthLatitude());
		visitDataDTO.setProductionLineId(technicalAssistance.getComboValueTAProductionLine().getId());
		visitDataDTO.setProyectCode(technicalAssistance.getProyectCode());
		visitDataDTO.setProyectName(technicalAssistance.getProyectName());
		visitDataDTO.setRuatId(technicalAssistance.getRuat().getId());
		visitDataDTO.setWestLongitude(technicalAssistance.getWestLongitude());
		
		
		List<TechnicalAssistanceVisit> tas =technicalAssistanceVisitDao.listByTechnicalAssistance(taId);
		//  cargar datos que vienen por visitas en las listas
		
		// P tipos de datos texto o combo
		// tipos de datos variables (colomnas agragadas dinammicamente)
		//for(TechnicalAssistanceVisit ts:tas){// cada una de las visitas de una asistencia tecnica
		for (int i = 0; i < tas.size(); i++) {
			
				TechnicalAssistanceVisit ts = tas.get(i);
				visitDataDTO.getIndex().add(i+1);
				visitDataDTO.getAnotherCropArea().add(new VisitDataItemDTO(1000L,ts.getAnotherCropArea(),ts.getId()));
				visitDataDTO.getAnotherProductiveLine().add(new VisitDataItemDTO(1000L,ts.getAnotherProductiveLine(),ts.getId()));
				visitDataDTO.getAnualProductionLevel().add(new VisitDataItemDTO(ts.getComboValueTAAnualProductionLevel().getId(),"",ts.getId()));
				visitDataDTO.getBpa().add(new VisitDataItemDTO(ts.getComboValueTABpa().getId(),"",ts.getId()));
				visitDataDTO.getCompilanceLevel().add(new VisitDataItemDTO(ts.getComboValueTACompilanceLevel().getId(),"",ts.getId()));
				visitDataDTO.getConsecutive().add(new VisitDataItemDTO(1000L,ts.getConsecutive(),ts.getId()));
				visitDataDTO.getFarmType().add(new VisitDataItemDTO(ts.getComboValueTAFarmType().getId(),"",ts.getId()));
				visitDataDTO.getFertilization().add(new VisitDataItemDTO(ts.getComboValueTAFertilization().getId(),"",ts.getId()));
				visitDataDTO.getMie().add(new VisitDataItemDTO(ts.getComboValueTAMie().getId(),"",ts.getId()));
				visitDataDTO.getMip().add(new VisitDataItemDTO(ts.getComboValueTAMip().getId(),"",ts.getId()));
				visitDataDTO.getProductionLastHarvest().add(new VisitDataItemDTO(1000L,ts.getProductionLastHarvest(),ts.getId()));
				visitDataDTO.getRecomendationsAndCommitments().add(new VisitDataItemDTO(1000L,ts.getRecomendationsAndCommitments(),ts.getId()));
				VisitDataItemDTO viDate = new VisitDataItemDTO(1000L,ts.getVisitDate().toString(),ts.getId());
				viDate.setValueDate(ts.getVisitDate());
				visitDataDTO.getVisitDate().add(viDate);
			//}	
			for(TechnicalAssistanceItem tai:ts.getTechnicalAssistanceItems()){ // cada item de una asistencia tecnica

				int fieldId = (int)((long)tai.getTechnicalAssistanceField().getId()); // el identificador de campo al que pertence el itm
				 switch(fieldId) {
				 case 10: 
				     System.out.println("fue 10");
				     putInRow(visitDataDTO.getRow10(),tai,i);
				     break;
				 case 20: 
					 System.out.println("fue 20");
					 putInRow(visitDataDTO.getRow20(),tai,i);
				     break;
				 case 30: 
					 System.out.println("fue 30");
					 putInRow(visitDataDTO.getRow30(),tai,i);
				     break;
				 case 40: 
					 System.out.println("fue 40");
					 putInRow(visitDataDTO.getRow40(),tai,i);
				     break;
				 case 50: 
					 System.out.println("fue 50");
					 putInRow(visitDataDTO.getRow50(),tai,i);
				     break;
				 default: 
					 System.out.println("default");
				     break;
				 }
			}			
		}
		return visitDataDTO;
	}
	
	
	public List<VisitDataRowDTO> putInRow(List<VisitDataRowDTO> row, TechnicalAssistanceItem tai, int position ){

	     if(row.size()==0){
	   		 VisitDataRowDTO visitDataRowDTONe = new VisitDataRowDTO ();
	   		 visitDataRowDTONe.setRowId(tai.getComboValueRowNameId().getId());
	   		 VisitDataItemDTO itemDTONe = new VisitDataItemDTO();
	   		 itemDTONe = VisitDataItemHelperDto.convertToRegisterDTO(tai);
	   		 for(int i = 0; i < position; i++){// agregar items en vacios hasta llegar a la posicion
	   			visitDataRowDTONe.getItems().add(new VisitDataItemDTO(5L)); 
	   		 }
	   		 visitDataRowDTONe.getItems().add(itemDTONe);
	   		 row.add(visitDataRowDTONe);			    	 
	     }
	     else{
		     //for(VisitDataRowDTO visitDataRowDTO: row){
		     for(int a = 0; a < row.size(); a++){
		    	 VisitDataRowDTO visitDataRowDTO = row.get(a);
		     //}
		    	 if(visitDataRowDTO.getRowId()==tai.getComboValueRowNameId().getId()){

		    		 VisitDataItemDTO itemDTO = new VisitDataItemDTO();
			   		 itemDTO = VisitDataItemHelperDto.convertToRegisterDTO(tai);	 
		    		 int i = visitDataRowDTO.getItems().size();
			   		 for(; i < position; i++){// agregar items en vacios hasta llegar a la posicion
			   			 	visitDataRowDTO.getItems().add(new VisitDataItemDTO(5L)); 
				   		 }
		    		 visitDataRowDTO.getItems().add(itemDTO);
		    		 break;		    		 	 
		    	 }
		    	 if(a==row.size()-1){
		    		 VisitDataRowDTO visitDataRowDTONe = new VisitDataRowDTO ();
		    		 visitDataRowDTONe.setRowId(tai.getComboValueRowNameId().getId());
		    		 VisitDataItemDTO itemDTONe = new VisitDataItemDTO();
			   		 itemDTONe = VisitDataItemHelperDto.convertToRegisterDTO(tai);
			   		 for(int i = 0; i < position; i++){// agregar items en vacios hasta llegar a la posicion
				   			visitDataRowDTONe.getItems().add(new VisitDataItemDTO(5L)); 
				   		 }		    		 
		    		 visitDataRowDTONe.getItems().add(itemDTONe);
		    		 row.add(visitDataRowDTONe);
		    		 break; 
		    	 }
		     }
	     }
	     
		return row;
	}


	@Override
	public void saveTechniclaAssitanceVistData(VisitDataDTO visitDataDTO, String userModifier) {
		TechnicalAssistance technicalAssistance = new TechnicalAssistance();
		technicalAssistance.setId(visitDataDTO.getId());
		technicalAssistance.setAltitude(visitDataDTO.getAltitude());
		technicalAssistance.setComboValueTAProductionLine(new ComboValue(visitDataDTO.getProductionLineId()));
		technicalAssistance.setCropArea(visitDataDTO.getCropArea());
		technicalAssistance.setNorthLatitude(visitDataDTO.getNorthLatitude());
		technicalAssistance.setProyectCode(visitDataDTO.getProyectCode());
		technicalAssistance.setProyectName(visitDataDTO.getProyectName());
		technicalAssistance.setRuat(new Ruat(visitDataDTO.getRuatId()));
		technicalAssistance.setWestLongitude(visitDataDTO.getWestLongitude());
		// metodo para guardar a technical Assistance
		technicalAssistanceDao.saveAndLog(technicalAssistance,userModifier);
		
		
		HashMap hashMapVisit = new HashMap<Long,TechnicalAssistanceVisit>();
		for(VisitDataItemDTO item:visitDataDTO.getAnotherCropArea()){
			getVisitEntity(item.getTechnicalAssistanceVisitId(), hashMapVisit).setAnotherCropArea(item.getValueTxt());		
		}		
		for(VisitDataItemDTO item:visitDataDTO.getAnotherProductiveLine()){
			getVisitEntity(item.getTechnicalAssistanceVisitId(), hashMapVisit).setAnotherProductiveLine(item.getValueTxt());		
		}
		for(VisitDataItemDTO item:visitDataDTO.getAnualProductionLevel()){
			getVisitEntity(item.getTechnicalAssistanceVisitId(), hashMapVisit).setComboValueTAAnualProductionLevel(new ComboValue(item.getValue()));		
		}
		for(VisitDataItemDTO item:visitDataDTO.getBpa()){
			getVisitEntity(item.getTechnicalAssistanceVisitId(), hashMapVisit).setComboValueTABpa(new ComboValue(item.getValue()));		
		}
		
		for(VisitDataItemDTO item:visitDataDTO.getCompilanceLevel()){
			getVisitEntity(item.getTechnicalAssistanceVisitId(), hashMapVisit).setComboValueTACompilanceLevel(new ComboValue(item.getValue()));		
		}
		
		for(VisitDataItemDTO item:visitDataDTO.getConsecutive()){
			getVisitEntity(item.getTechnicalAssistanceVisitId(), hashMapVisit).setConsecutive(item.getValueTxt());		
		}
		
		for(VisitDataItemDTO item:visitDataDTO.getFarmType()){
			getVisitEntity(item.getTechnicalAssistanceVisitId(), hashMapVisit).setComboValueTAFarmType(new ComboValue(item.getValue()));		
		}		
		
		for(VisitDataItemDTO item:visitDataDTO.getFertilization()){
			getVisitEntity(item.getTechnicalAssistanceVisitId(), hashMapVisit).setComboValueTAFertilization(new ComboValue(item.getValue()));		
		}	
		
		for(VisitDataItemDTO item:visitDataDTO.getMie()){
			getVisitEntity(item.getTechnicalAssistanceVisitId(), hashMapVisit).setComboValueTAMie(new ComboValue(item.getValue()));		
		}	
		
		for(VisitDataItemDTO item:visitDataDTO.getMip()){
			getVisitEntity(item.getTechnicalAssistanceVisitId(), hashMapVisit).setComboValueTAMip(new ComboValue(item.getValue()));		
		}	
		
		for(VisitDataItemDTO item:visitDataDTO.getProductionLastHarvest()){
			getVisitEntity(item.getTechnicalAssistanceVisitId(), hashMapVisit).setProductionLastHarvest(item.getValueTxt());		
		}	
		
		for(VisitDataItemDTO item:visitDataDTO.getRecomendationsAndCommitments()){
			getVisitEntity(item.getTechnicalAssistanceVisitId(), hashMapVisit).setRecomendationsAndCommitments(item.getValueTxt());		
		}	
		
		for(VisitDataItemDTO item:visitDataDTO.getVisitDate()){
				//Date date = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss.SSSZ", Locale.ENGLISH).parse(item.getValueTxt());
				getVisitEntity(item.getTechnicalAssistanceVisitId(), hashMapVisit).setVisitDate(item.getValueDate());
		}
		Collection<TechnicalAssistanceVisit> co = hashMapVisit.values();
		for(TechnicalAssistanceVisit visit:co){
			visit.setTechnicalAssistance(technicalAssistance);
			technicalAssistanceVisitDao.saveAndLog(visit, userModifier);
		
		}

			
		
		//TODO hacer las entiades de visit item dto y hacer los inserts
//		HashMap hashMap = new HashMap<Long,List<VisitDataItemDTO>>();
//		putInListOfHashMap(hashMap,getListFromRowDTO(visitDataDTO.getRow10()));
//		putInListOfHashMap(hashMap,getListFromRowDTO(visitDataDTO.getRow20()));
//		putInListOfHashMap(hashMap,getListFromRowDTO(visitDataDTO.getRow30()));
//		putInListOfHashMap(hashMap,getListFromRowDTO(visitDataDTO.getRow40()));
//		putInListOfHashMap(hashMap,getListFromRowDTO(visitDataDTO.getRow50()));
//		Collection<VisitDataItemDTO> coitem = hashMap.values();
//		for(VisitDataItemDTO item:coitem){
//			TechnicalAssistanceItem entItem = new TechnicalAssistanceItem();
//			
//		}

		List<VisitDataItemDTO> listVisit = new ArrayList<VisitDataItemDTO>();
		listVisit.addAll(getListFromRowDTO(visitDataDTO.getRow10()));
		listVisit.addAll(getListFromRowDTO(visitDataDTO.getRow20()));
		listVisit.addAll(getListFromRowDTO(visitDataDTO.getRow30()));
		listVisit.addAll(getListFromRowDTO(visitDataDTO.getRow40()));
		listVisit.addAll(getListFromRowDTO(visitDataDTO.getRow50()));
		
		List<TechnicalAssistanceItem> entityItems = new ArrayList<TechnicalAssistanceItem>();
		for(VisitDataItemDTO viDto:listVisit){
			TechnicalAssistanceItem entity = new TechnicalAssistanceItem();
			entity.setComboValueRowNameId(new ComboValue(viDto.getRowId()));
			entity.setComboValueRowValueId(new ComboValue(viDto.getValue()));
			entity.setId(viDto.getId());
			entity.setRowValueTxt(viDto.getValueTxt());
			entity.setTechnicalAssistanceField(new TechnicalAssistanceField(viDto.getFieldId()));
			entity.setTechnicalAssistanceVisit(new TechnicalAssistanceVisit(viDto.getTechnicalAssistanceVisitId()));
			if(entity.getId()!=null){// los que se crearon de relleno no tienen id
				entityItems.add(entity);
			}
		}
		for(TechnicalAssistanceItem entity:entityItems){
			technicalAssistanceItemDao.saveAndLog(entity, userModifier);
		}
		
		
		
	}
	public void putInListOfHashMap(HashMap<Long,List<VisitDataItemDTO>> store, List<VisitDataItemDTO> items){
		for(VisitDataItemDTO item: items){
			if(store.containsKey(item.getTechnicalAssistanceVisitId())){
				store.get(item.getTechnicalAssistanceVisitId()).add(item);
			}else{
				List<VisitDataItemDTO> newList = new ArrayList<VisitDataItemDTO>();
				newList.add(item);
				store.put(item.getTechnicalAssistanceVisitId(), newList);
			}
		}
	}
	
	public List<VisitDataItemDTO> getListFromRowDTO(List<VisitDataRowDTO> rows){
		List<VisitDataItemDTO> returnList = new ArrayList<VisitDataItemDTO>();
		for(VisitDataRowDTO row:rows){
			returnList.addAll(row.getItems());
		}
		return returnList;
	}
	
	public TechnicalAssistanceVisit getVisitEntity(Long visitId, HashMap<Long,TechnicalAssistanceVisit> store){
		if(!store.containsKey(visitId)){
			store.put(visitId,new TechnicalAssistanceVisit(visitId));
		}
		return store.get(visitId);
	}
}
